package demo4;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-05-08
 * Time: 18:54
 */
class Student implements Comparable<Student> {
    private String name;
    private int score;
    private int age;

    public Student(String name, int score, int age) {
        this.name = name;
        this.score = score;
        this.age = age;
    }

    //实现toString方法，也是多态的思想
    @Override
    public String toString() {
        return "{" + this.name + "-" + this.age + "-" + this.score + "}";
    }

    @Override
    public int compareTo(Student o) {
        //按年龄排序
        /*if (this.age - o.age > 0) {
            return 1;
        } else if (this.age - o.age < 0) {
            return -1;
        } else {
            return 0;
        }*/

        //按名字排序
        if(this.name.compareTo(o.name) > 0){
            return 1;
        }else if(this.name.compareTo(o.name) < 0){
            return -1;
        }else{
            return 0;
        }
    }
}

public class Testdemo1 {
    public static void sort(Comparable[] array){
        //使用冒泡排序
        for (int i = 0; i < array.length-1; i++) {
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j].compareTo(array[j+1]) > 0){
                    //交换
                    Comparable tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("z三", 192, 20);
        students[1] = new Student("l四", 183, 40);
        students[2] = new Student("w五", 120, 34);

        //Arrays.sort(students);
        sort(students);
        System.out.println(Arrays.toString(students));
    }


}
